package com.fantasychong.myandroidapplication.recyclerView;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.fantasychong.myandroidapplication.R;

import java.util.List;

/**
 * 主页列表的adapter
 * Created by Fantasychong
 * Date: 2023/1/28
 */
public class RecyclerViewAdapter extends androidx.recyclerview.widget.RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {


    private final Context context;
    private final onItemViewClickListener listener;
    private List<RecyclerViewBean> list;

    public RecyclerViewAdapter(Context context, List<RecyclerViewBean> list, onItemViewClickListener listener) {
        this.context = context;
        this.list = list;
        this.listener = listener;
    }

    @NonNull
    @Override
    public RecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recyclerview, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
        holder.titleTv.setText(list.get(position).getTitle());
        holder.contentTv.setText(list.get(position).getContent()+ (position+1));
        holder.layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener!= null){
                    listener.onItemClick(position);
                }
            }
        });

        LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) holder.picIv.getLayoutParams();
        params.height= list.get(position).getHeight();
        holder.picIv.setLayoutParams(params);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class ViewHolder extends androidx.recyclerview.widget.RecyclerView.ViewHolder{

        private final TextView titleTv;
        private final TextView contentTv;
        private final LinearLayout layout;
        private final ImageView picIv;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            layout= itemView.findViewById(R.id.item_layout);
            titleTv= itemView.findViewById(R.id.item_titleTv);
            contentTv= itemView.findViewById(R.id.item_contentTv);
            picIv= itemView.findViewById(R.id.item_picIv);
        }
    }

    public interface onItemViewClickListener{
        void onItemClick(int position);
    }
}
